package com.itown.expo.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.criterion.DetachedCriteria;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.ModelAndView;

import webframe.common.dao.Pagination;
import webframe.common.file.ExportDataHelper;
import webframe.common.file.RowMapperFactory;
import webframe.common.helper.ControllerHelper;

import com.itown.expo.controller.base.MyBaseCommandController;
import com.itown.expo.helper.MyControllerHelper;
import com.itown.expo.model.Decl;
import com.itown.expo.model.Goods;

public class StatGoodsExportExcelController extends MyBaseCommandController {
	private RowMapperFactory rowMapperFactory;

	public RowMapperFactory getRowMapperFactory() {
		return rowMapperFactory;
	}

	public void setRowMapperFactory(RowMapperFactory rowMapperFactory) {
		this.rowMapperFactory = rowMapperFactory;
	}

	@Override
	protected ModelAndView handleInner(HttpServletRequest request,
			HttpServletResponse response, Object command)
			throws RuntimeException {
		Goods cgoods = (Goods) command;
		DetachedCriteria criteria = MyControllerHelper
				.getGoodsDetachedCriteria(cgoods);
		StatGoodsController.applyCriteria(getServiceContainer()
				.getCheckBizService(), criteria, cgoods);
		Pagination page = ControllerHelper.queryTotalCountWithSql(criteria);
		Object[] arrs = page.getSqlAndParams(true);
		String where = (String) arrs[0];
		Object[] params = (Object[]) arrs[1];

		String declSql = "select * from Decl d where d.decl_no in (select distinct t.decl_no from goods t "
				+ where + ") order by d.decl_no asc";

		String goodsSql = "select * from goods t " + where
				+ " order by t.decl_no asc, t.goods_no asc";

		WebApplicationContext wc = getWebApplicationContext();

		List<Decl> declList = ExportDataHelper.preformQuery(declSql, params,
				getRowMapperFactory().getRowMapper(wc, Decl.class));
		List<Goods> goodsList = ExportDataHelper.preformQuery(goodsSql, params,
				getRowMapperFactory().getRowMapper(wc, Goods.class));

		for (Decl decl : declList) {
			for (Goods goods : goodsList) {
				if (decl.getDeclNo().equals(goods.getDeclNo())) {
					decl.setFirstGoods(goods);
					break;
				}
			}
		}
		Map map = new HashMap();
		map.put("declList", declList);
		map.put("goodsList", goodsList);

		return new ModelAndView("StatGoodsListExcelView", map);

	}

}
